/*
 * EOLTestView.java
 */

package com.zentello.sbot.gui;

import java.io.File;
import java.util.List;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import com.zentello.sbot.Eval;
import com.zentello.sbot.SimpleTestSuiteObserver;
import com.zentello.sbot.TestSuiteObserver;
import com.zentello.util.Log;
import java.awt.Color;
import java.awt.Toolkit;
import java.beans.PropertyChangeEvent;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeListener;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.SwingWorker;
import static com.zentello.util.Log.*;
/**
 * The application's main frame.
 */
public class EOLTestView extends FrameView implements /*ActionListener,*/ PropertyChangeListener {
    private String[] args;

    private void validateArgs(){
        if(args.length == 1 && new File(args[0]).exists()){
            configurationLabel.setText(args[0]);
            startButton.setEnabled(true);
        }
        else{
            configurationLabel.setText(" ");        
            startButton.setEnabled(false);
        }
        
    }
    public EOLTestView(SingleFrameApplication app, String[] args) {
        super(app);
        this.args = args;
        initComponents();
        validateArgs();
        initExtra();
        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {
            public void actionPerformed(ActionEvent e) {

            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");

        // connecting action tasks to status bar via TaskMonitor
    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = EOLTestApp.getApplication().getMainFrame();
            aboutBox = new EOLTestAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        EOLTestApp.getApplication().show(aboutBox);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        statusTextArea = new javax.swing.JTextArea();
        jPanel1 = new javax.swing.JPanel();
        startButton = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        configurationLabel = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jProgressBar1 = new javax.swing.JProgressBar();
        greenlightPanel = new javax.swing.JPanel();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();

        mainPanel.setName("mainPanel"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        statusTextArea.setColumns(20);
        statusTextArea.setEditable(false);
        statusTextArea.setLineWrap(true);
        statusTextArea.setRows(5);
        statusTextArea.setName("statusTextArea"); // NOI18N
        jScrollPane1.setViewportView(statusTextArea);

        jPanel1.setName("jPanel1"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(com.zentello.sbot.gui.EOLTestApp.class).getContext().getActionMap(EOLTestView.class, this);
        startButton.setAction(actionMap.get("startStopButtonAction")); // NOI18N
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(com.zentello.sbot.gui.EOLTestApp.class).getContext().getResourceMap(EOLTestView.class);
        startButton.setText(resourceMap.getString("startButton.text")); // NOI18N
        startButton.setToolTipText(resourceMap.getString("startButton.toolTipText")); // NOI18N
        startButton.setName("startButton"); // NOI18N
        startButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                startButtonActionPerformed(evt);
            }
        });

        jButton2.setAction(actionMap.get("configButtonAction")); // NOI18N
        jButton2.setText(resourceMap.getString("jButton2.text")); // NOI18N
        jButton2.setToolTipText(resourceMap.getString("jButton2.toolTipText")); // NOI18N
        jButton2.setName("jButton2"); // NOI18N

        configurationLabel.setFont(resourceMap.getFont("configurationLabel.font")); // NOI18N
        configurationLabel.setText(resourceMap.getString("configurationLabel.text")); // NOI18N
        configurationLabel.setName("configurationLabel"); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(startButton)
                .addGap(18, 18, 18)
                .addComponent(jButton2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(configurationLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 473, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(configurationLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(startButton))
                .addContainerGap(2, Short.MAX_VALUE))
        );

        jPanel2.setName("jPanel2"); // NOI18N

        jProgressBar1.setMaximumSize(new java.awt.Dimension(146, 14));
        jProgressBar1.setName("jProgressBar1"); // NOI18N

        greenlightPanel.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        greenlightPanel.setMaximumSize(new java.awt.Dimension(28, 34));
        greenlightPanel.setMinimumSize(new java.awt.Dimension(28, 34));
        greenlightPanel.setName("greenlightPanel"); // NOI18N

        javax.swing.GroupLayout greenlightPanelLayout = new javax.swing.GroupLayout(greenlightPanel);
        greenlightPanel.setLayout(greenlightPanelLayout);
        greenlightPanelLayout.setHorizontalGroup(
            greenlightPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 22, Short.MAX_VALUE)
        );
        greenlightPanelLayout.setVerticalGroup(
            greenlightPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 8, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jProgressBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 581, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(greenlightPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(10, 10, 10))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(greenlightPanel, 0, 14, Short.MAX_VALUE))
                .addContainerGap())
        );

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 625, Short.MAX_VALUE)
                        .addContainerGap())
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addContainerGap())))
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 395, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        menuBar.setName("menuBar"); // NOI18N

        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        setComponent(mainPanel);
        setMenuBar(menuBar);
    }// </editor-fold>//GEN-END:initComponents

    private void startButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startButtonActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_startButtonActionPerformed

    boolean running = false;
    @Action
    public void startStopButtonAction() {
        if(running){
            stopTest();
        }
        else{
            startTest();
        }
    }
    
    public void startTest(){
        running = true;
        startButton.setText("Stop");        
        task = new Task();
        task.addPropertyChangeListener(this);
        task.execute();
        debug("Run test");        
    }
    
    public void popUpResult(boolean result){
        String message = result?"The test was successful!\r\nDisconnect the unit and apply appropriate labels.":"The test failed. See log for more information.\r\nDisconnect the unit to resolve issues.";
        JOptionPane.showMessageDialog(this.getFrame(), message);
    }

    public void stopTest() {
        int option = JOptionPane.showConfirmDialog(this.getFrame(), "This will terminate the current test. Reset?");    
        if(option == JOptionPane.YES_OPTION && task!=null){
            task.cancel(true);
            running = false;
            startButton.setText("Start");        
            
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel configurationLabel;
    private javax.swing.JPanel greenlightPanel;
    private javax.swing.JButton jButton2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JProgressBar jProgressBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JButton startButton;
    private javax.swing.JTextArea statusTextArea;
    // End of variables declaration//GEN-END:variables

    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;

    private JDialog aboutBox;

    
    private Task task;

    public void propertyChange(PropertyChangeEvent evt) {
        if ("progress".equals(evt.getPropertyName())) {
            int progress = (Integer) evt.getNewValue();
            debug("progress " + progress);
            jProgressBar1.setValue(progress);
        } 
        
    }

    private void initExtra() {
        startButton.setText("Start");
    }
 
    class Task extends SwingWorker<Void, Void>{
        int progress=0;
        boolean result;
        Eval e;
        /*
         * Main task. Executed in background thread.
         */
        @Override
        public Void doInBackground() {
            result = false;
            greenlightPanel.setBackground(Color.yellow);
            e = new Eval(new Observer(this), args);
            jProgressBar1.setEnabled(true);
            jProgressBar1.setMaximum(e.getTestCount());
            progress=0;
            setProgress(0);
            e.run();
            return null;
        }
        
        void progress(int progress){
            setProgress(progress);
        }
        /*
         * Executed in event dispatching thread
         */
        @Override
        public void done() {
            if(e!=null){
                e.stop();
            }
            Toolkit.getDefaultToolkit().beep();
            startButton.setText("Start");
            running = false;
            jProgressBar1.setValue(0);
            popUpResult(result);
        }

        class Observer extends  TestSuiteObserver{
            private Task task;
            private boolean result;

            Observer(Task task){
                this.task = task;
            }
            int progress = 0;

            public void testFinished(String name, boolean pass) {
                progress++;
                Log.debug("" + progress);
                log((pass?"PASS:":"FAILED:") + name + "\r\n");
                task.progress(progress);

            }

            public void testFailed(String name) {
                greenlightPanel.setBackground(Color.red);
            }

            public void setupFailed(String name) {
                greenlightPanel.setBackground(Color.red);
            }

            public void teardownFailed(String name) {
                greenlightPanel.setBackground(Color.red);
            }

            public void suiteFinished(boolean result) {
                greenlightPanel.setBackground(result?Color.GREEN:Color.RED);
                this.result = result;
            }

            public void log(String message) {
                statusTextArea.append(message);
                statusTextArea.setCaretPosition( statusTextArea.getText().length() );
            }

            public void setup(List<String> args) {
            }

            public void teardown() {
            }
        }
    }
    final JFileChooser fc = new JFileChooser();
    boolean configFileSelected = false;
    @Action
    public void configButtonAction() {
        if(!configFileSelected){
            fc.setCurrentDirectory(new File("."));
            configFileSelected = true;
        }
        //In response to a button click:
        int returnVal = fc.showOpenDialog(this.getFrame());
        if(returnVal == JFileChooser.APPROVE_OPTION){
            this.args = new String[] {fc.getSelectedFile().getPath()};    
            validateArgs();
        }
    }

}
